package leetcode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0347.java
 * @Author : WangRuoyu
 * @Date 2023/11/9 18:12
 */


public class Q0347 {
    public int[] topKFrequent(int[] nums, int k) {
        int[] res = new int[k];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i : nums) {
            if (!map.containsKey(i)) {
                map.put(i, 1);
            } else {
                map.put(i, map.get(i) + 1);
            }
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(map::get));
        for (Integer i : map.keySet()) {
            pq.add(i);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        int index = 0;
        for (Integer i : pq) {
            res[index++] = i;
        }
        return res;
    }

    public static void main(String[] args) {
        Q0347 sl = new Q0347();
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;
        System.out.println(Arrays.toString(sl.topKFrequent(nums, k)));
    }
}